<template>
  <div class="chat-page">
    <view-top></view-top>
    <el-row>
      <el-col :span="8">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span class="header-title">好友列表</span>
            <!-- 添加按钮 -->
            <el-button type="primary" @click="showAddFriendDialog = true" style="float: right;">好友操作</el-button>
          </div>
          <el-scrollbar wrap-class="scrollbar-wrapper">
            <el-menu
              default-active="2"
              class="el-menu-vertical-demo"
              @open="handleOpen"
              @close="handleClose"
            >
              <el-menu-item
                v-for="friend in friends"
                :key="friend.id"
                @click="selectFriend(friend)"
                :class="friend.class"
              >
                <el-avatar :src="friend.friendAvatar" size="40"></el-avatar>
                <span slot="title">{{ friend.friendName }}</span>
                <span v-if="friend.online" class="online-status">在线</span>
                <span v-else class="offline-status">离线</span>
              </el-menu-item>
            </el-menu>
          </el-scrollbar>
        </el-card>
      </el-col>
      <el-col :span="16">
        <!-- 展示好友动态 -->
        <el-card class="box-card" v-if="selectedFriend">
          <div slot="header" class="clearfix">
            <span class="header-title">{{ selectedFriend.friendName }}的动态</span>
          </div>
          <div v-for="post in friendPosts" :key="post.lastReadTime">
           
            
            <p class="post-content">
              <!-- 展示用户头像 -->
              <!-- <el-avatar :src="post.avatar" size="30" style="margin-right: 10px;"></el-avatar> -->
              <!-- 显示用户名 -->
              <span style="color: #333; font-weight: bold;">{{ post.userName }}</span>
              <!-- 显示阅读信息 -->
              <span style="color: #999;" >阅读了</span>
              <span style="color: #007BFF;" class="cursor" @click="jumpToReader(post)">{{ post.novelName }}</span>
              <span style="color: #999;"class="cursor" @click="jumpToReader(post)" > - </span>
              <span style="color: #007BFF;"class="cursor" @click="jumpToReader(post)">{{ post.lastReadTitle }}</span>
              <span style="color: #999;"> 于 </span>
              <!-- 显示阅读时间 -->
              <span style="color: #999;">{{ post.lastReadTime }}</span>
            </p>
          </div>
        </el-card>
        <!-- 聊天窗口 -->
        <el-card class="box-card" v-if="selectedFriend">
          <div slot="header" class="clearfix">
            <span class="header-title">聊天窗口</span>
          </div>
          <el-scrollbar wrap-class="scrollbar-wrapper">
            <div v-for="message in selectedMessages" :key="message.id" class="message" :class="{ 'self-message': message.userName === username }">
              <el-avatar :src="message.avatar" size="40"></el-avatar>
              <div class="message-content">
                <div class="message-header">
                  <span class="message-username"><strong>{{ message.userName }}</strong></span>
                  <span class="message-time">{{ message.createTime }}</span>
                </div>
                <!-- 显示消息内容和消息状态 -->
                <div class="message-body">
                  <span class="message-text">{{ message.content }}</span>
                  <span class="message-status">{{ message.status === 1 ? '已读' : '未读' }}</span>
                </div>
              </div>
            </div>
          </el-scrollbar>
          <el-card class="box-card input-card">
            <div slot="header" class="clearfix">
              <span class="header-title">输入框</span>
            </div>
            <el-input v-model="newMessage" placeholder="输入消息内容" class="input-box"></el-input>
            <el-button type="primary" @click="sendMessage" class="send-button">发送</el-button>
          </el-card>
        </el-card>
      </el-col>
    </el-row>
    <!-- 添加对话框 -->
    <el-dialog
      :visible.sync="showAddFriendDialog"
      title="添加好友"
      @close="resetAddFriendInput"
    >
      <template>
        <div style="padding: 20px;"> <!-- 添加内边距 -->
          <el-input
            v-model="newFriendName"
            placeholder="请输入好友名"
          ></el-input>
        </div>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddFriendDialog = false">取消</el-button>
          <el-button type="primary" @click="addFriend">添加</el-button>
          <el-button type="primary" @click="deleteFriend">删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import ViewTop from './ViewTop.vue';
export default {
  components: {
    ViewTop
  },
  data() {
    return {
      friends: [],
      selectedFriend: null,
      previousSelectedFriend: null, // 新增：记录上一个选中的朋友
      messages: [],
      selectedMessages: [],
      newMessage: '',
      socket: null,
      username: JSON.parse(sessionStorage.getItem('user')).username,
      showAddFriendDialog: false,//控制对话框隐藏
      newFriendName: '',//新增：输入框
      friendPosts: [] // 新增：存储好友动态
    };
  },
  mounted() {
    this.axios.get('/user/friend/list').then(response => {
      this.friends = response.data.data.map(friend => ({
        ...friend,
        online: false
      }));
      //过去会话消息
      this.axios.get('/user/chat/list?friendName='+this.username).then(response1 => {
        this.messages = response1.data.data;
        console.log(this.messages);
      });
      //获取是否有新消息
      this.friends.forEach(friend => {
        const friendMessages = this.messages.filter(m => m.userName === friend.friendName);
        const hasUnread = friendMessages.some(m => m.status === 0);
        this.$set(friend, 'onLook', !hasUnread);
        if (!friend.onLook) {
          this.$set(friend, 'class', 'new-message');
          console.log("触发");
        }
      }
      );
      //建立连接
      this.socket = new WebSocket(`ws://localhost:8087/chat?username=${this.username}`);
      this.socket.onopen = () => {
        console.log('WebSocket connection established');
      };
      this.socket.onmessage = this.handleMessage;
      this.socket.onclose = this.handleClose;
    }).catch(error => {
      console.error(error);
    });
  },
  methods: {
    jumpToReader(post){
      var that=this
      var book;
      var chapters;
      var cid=post.lastRead;
      this.axios({
        method: "get",
        url: "/user/novel/list?id="+post.novelId,
      }).then((res)=>{
        console.log(res.data.data)
        book=res.data.data[0]
        this.axios({
            method: "get",
            url: "/user/chapter/directory?id=" + book.id,
          }).then((res1) => {
            chapters = res1.data.data;
            this.$router.push({
              path: "/reader",
              query: {
                chapters: JSON.stringify(chapters),
                book: JSON.stringify(book),
                cid: JSON.stringify(cid)
              }
            })
          }).catch((err1) => {
            console.log(err1);
          });
        }).catch((err)=>{
          console.log(err)
      })
      
    },
    handleOpen(key, keyPath) {
      console.log(key, keyPath);
    },
    handleClose(key, keyPath) {
      console.log(key, keyPath);
    },
    selectFriend(friend) {
      // 如果有上一个选中的朋友，恢复其原来的颜色
      if (this.previousSelectedFriend) {
        const hasUnread = this.messages.some(m => m.userName === this.previousSelectedFriend.friendName && m.status === 0);
        this.$set(this.previousSelectedFriend, 'class', hasUnread ? 'new-message' : '');
      }
      this.selectedFriend = friend;
      this.previousSelectedFriend = friend; // 更新上一个选中的朋友
      this.update().then(() => {
        console.log("选中朋友");
        this.$set(this.selectedFriend, 'class', 'new-message selected');
        // 获取好友动态
        console.log(friend)
        this.getFriendPosts(friend.friendId); 
      });
    },
    getMessage() {
      return new Promise((resolve, reject) => {
        if(this.selectedFriend==null)
          return;
        // 过去会话消息
        this.axios.get('/user/chat/list?friendName=' + this.selectedFriend.friendName).then(response1 => {
          this.messages = response1.data.data;
          console.log(this.messages);
          // 过滤出与所选朋友的聊天消息
          this.selectedMessages = this.messages.filter(message => {
            return (message.userName === this.selectedFriend.friendName || message.userName === this.username);
          });
          console.log(this.selectedMessages);
          // 清除新消息标记
          this.friends.forEach(f => {
            if (f.id === this.selectedFriend.id) {
              f.onLook = true;
              // 移除 .new-message 类，添加 .new-message.clicked 类
              this.$set(f, 'class', 'new-message clicked');
            }
          });
          resolve(); // 请求成功，解决 Promise
        }).catch(error => {
          console.error(error);
          reject(error); // 请求失败，拒绝 Promise
        });
      });
    },
    update() {
      // 返回一个 Promise
      return new Promise((resolve, reject) => {
        this.axios({
          method: 'post',
          url: '/user/chat/update',
          data: {
            userName: this.selectedFriend.friendName
          }
        }).then(res => {
          if (res.data.code === 1) {
            console.log("更新成功");
          }
          this.sendUpdate();
          // 调用 getMessage 方法并等待其完成
          this.getMessage().then(() => {
            // 解决 Promise
            resolve();
          }).catch(error => {
            console.error(error);
            reject(error);
          });
        }).catch(error => {
          console.error(error);
          // 拒绝 Promise
          reject(error);
        });
      });
    },
    likePost(post) {
      post.likes++;
    },
    commentPost(post) {
      // 实现评论功能
    },
    sendMessage() {
      if (this.socket.readyState === WebSocket.OPEN) {
        this.socket.send(this.username + ":" + this.selectedFriend.friendName + ":" + this.newMessage);
        this.selectedMessages.push({
          userName: this.username,
          content: this.newMessage,
          status: 0
        });
        this.newMessage = '';
      } else {
        console.error('WebSocket is not open. Cannot send message.');
      }
    },
    sendUpdate(){
      if (this.socket.readyState === WebSocket.OPEN) {
        this.socket.send(this.username + ":" + this.selectedFriend.friendName + ":" + "$update");
      } else {
        console.error('WebSocket is not open. Cannot send message.');
      }
    },
    sendFriendUpdate(){
      if (this.socket.readyState === WebSocket.OPEN) {
        if(this.selectedFriend==null)
          this.socket.send(this.username + ":" + "none" + ":" + "$friendUpdate");
        else
          this.socket.send(this.username + ":" + this.selectedFriend.friendName + ":" + "$friendUpdate");
      } else {
        console.error('WebSocket is not open. Cannot send message.');
      }
    },
    handleMessage(event) {
      try{
        const message = JSON.parse(event.data);
        console.log("type---------",message.type)
        if (message.type === 1) {
          // 更新好友列表中的在线状态
          const onlineUsers = message.content.split(',');
          console.log("onlineUsers",onlineUsers);
          console.log("friends",this.friends);
          this.friends.forEach(friend => {
              friend.online = onlineUsers.includes(friend.friendName);
              console.log(friend.online)
          });
        } else if (message.type === 2) {
          // 更新单个用户的在线状态
          const friend = this.friends.find(f => f.friendName === message.userName);
          if (friend) {
              this.$set(friend, 'online', true);
          }
          console.log(friend,"上线")
        } else if (message.type === 3) {
          // 更新单个用户的在线状态
          const friend = this.friends.find(f => f.friendName === message.userName);
          if (friend) {
            this.$set(friend, 'online', false);
          }
          console.log(friend,"离线")
        } 
        else if(message.type===4){
          // 处理其他类型的消息
          this.messages.push(message);
          console.log('Received message:', message);
          // 标记有新消息的好友
          this.friends.forEach(friend => {
            if (friend.friendName === message.userName) {
              this.$set(friend, 'onLook', false);
              if (!friend.onLook) {
                this.$set(friend, 'class', 'new-message');
                console.log("触发");
              }
            }
          });
          // 如果当前选中的朋友发送消息，更新所选消息列表
          if (this.selectedFriend && message.userName === this.selectedFriend.friendName) {
            this.update();
          }
        }else if(message.type===5){
          this.getMessage();
        }else{
          // 更新好友列表
          this.axios.get('/user/friend/list').then(response => {
              this.friends = response.data.data.map(friend => ({
                ...friend,
                online: false
              }));
              // 更新好友列表中的在线状态
              const onlineUsers = message.content.split(',');
              console.log("onlineUsers",onlineUsers);
              console.log("friends",this.friends);
              this.friends.forEach(friend => {
                  friend.online = onlineUsers.includes(friend.friendName);
                  console.log(friend.online)
              });
            });
        }
      }catch(e){
        console.log(e);
      }
      
    },
    handleClose(event) {
      console.log('WebSocket closed:', event);
    },
    // 添加 addFriend 方法
    addFriend() {
      if (!this.newFriendName) {
        this.$message.warning('请输入好友名');
        return;
      }
      // 添加好友
      this.axios.post('/user/friend/add', { name: this.newFriendName })
        .then(response => {
          if (response.data.code === 1) {
            // 添加成功，弹出消息提示
            this.$message.success('添加好友成功');
            this.showAddFriendDialog = false;
            this.resetAddFriendInput();
            this.sendFriendUpdate();
          } else {
            // 添加失败，弹出消息提示
            this.$message.error(response.data.msg);
          }
        })
        .catch(error => {
          console.error('添加好友出错:', error);
          this.$message.error('添加好友出错，请稍后重试');
        });
    },
    deleteFriend(){
      if (!this.newFriendName) {
        this.$message.warning('请输入好友名');
        return;
      }
      // 删除好友
      this.axios.delete('/user/friend/delete', {
        data:{
          name: this.newFriendName
         }
      })
        .then(response => {
          if (response.data.code === 1) {
            // 删除成功，弹出消息提示
            this.$message.success('删除好友成功');
            this.showAddFriendDialog = false;
            this.resetAddFriendInput();
            this.sendFriendUpdate();
          } else {
            // 删除失败，弹出消息提示
            this.$message.error(response.data.msg);
          }
        })
        .catch(error => {
          console.error('删除好友出错:', error);
          this.$message.error(response.data.msg);
        });
    },
    // 重置输入框内容
    resetAddFriendInput() {
      this.newFriendName = '';
    },
    // 新增：获取好友动态
    getFriendPosts(id) {
      var that=this;
      this.axios.get('/user/readingHistory/listAll?id='+id).then(response => {
        this.friendPosts = response.data.data;
        console.log('好友动态:', this.friendPosts);
        this.friendPosts=response.data.data;
      }).catch(error => 
        console.log(error)
      )
    }
  }
};
</script>

<style scoped>
/* 消息头部样式，包含用户名和时间 */
.message-header {
  margin-bottom: 5px;
}

/* 用户名样式 */
.message-username {
  font-size: 14px;
  font-weight: bold;
  color: #333;
}

/* 时间样式，字体颜色浅淡且比用户名小 */
.message-time {
  font-size: 12px;
  color: #999;
  margin-left: 5px;
}

/* 消息主体样式，包含消息内容和状态 */
.message-body {
  display: flex;
  align-items: center;
}

/* 消息内容样式 */
.message-text {
  font-size: 14px;
  color: #333;
}

/* 消息状态样式，和消息内容一行，样式和时间差不多 */
.message-status {
  font-size: 12px;
  color: #999;
  margin-left: 5px;
}
.chat-page {
  margin: 20px;
  font-family: 'Arial', sans-serif;
}

.box-card {
  margin-bottom: 20px;
  border-radius: 0;
  box-shadow: none;
  border: 1px solid #e6e6e6;
}

.scrollbar-wrapper {
  height: 400px;
}

.header-title {
  font-size: 16px;
  font-weight: normal;
  color: #333;
  padding: 10px;
  border-bottom: 1px solid #e6e6e6;
}

.post-content {
  font-size: 14px;
  color: #333;
  margin: auto;
  text-align: left;
  padding: 10px;
}

.post-image {
  border-radius: 0;
  margin-bottom: 10px;
  width: 100%;
}

.post-button {
  margin-right: 10px;
  color: #007BFF;
  cursor: pointer;
  border: none;
  background: none;
  padding: 0;
}
.cursor{
  cursor: pointer;
}
.online-status {
  color: green;
  margin-left: 10px;
}

.offline-status {
  color: red;
  margin-left: 10px;
}

.message {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
  padding: 10px;
}

.message.self-message {
  justify-content: flex-end;
}

.message-content {
  margin-left: 10px;
}

.message-username {
  font-size: 14px;
  font-weight: normal;
  color: #333;
}

.message-text {
  font-size: 14px;
  color: #333;
}

.input-card {
  border-top: 1px solid #e6e6e6;
}

.input-box {
  margin-bottom: 10px;
  border: 1px solid #e6e6e6;
  border-radius: 5px;
  padding: 10px;
}

.send-button {
  width: 100%;
  background-color: #007BFF;
  color: #fff;
  border: none;
  border-radius: 5px;
  padding: 10px;
  cursor: pointer;
}

.new-message {
  background-color: rgb(249, 98, 98); /* 新消息的背景颜色 */
}
.new-message.clicked {
  background-color: #fff; /* 点击后的背景颜色 */
}
.new-message.selected {
  background-color: #87bef5; /* 选中的消息的背景颜色 */
}
</style>
